#!/usr/bin/env bash

guess_proxy_address()
{
	virt=$(systemd-detect-virt)
	# gateway=$(ip route show  default | awk '{ print $3 }')
	local_ip=$(hostname -I | awk '{ print $1}')
	case $virt in
	vmware)	# for local *nix on vmware and wsl
		hyper_host=$(awk -F"." '{print $1"."$2"."$3".1"}' <<< $local_ip)
		echo "http://${hyper_host}:7890"
		;;
	wsl)
		gateway=$(ip route show default | awk '{print $3}')
		echo "http://${gateway}:7890"
		;;
	*)	# for others system need local proxy. e.g. vps
		echo "http://${local_ip}:7890"
		;;
	esac
}

main()
{
	if [ -z $1 ]; then
		proxy_address=$(guess_proxy_address)
	else
		proxy_address=$1
	fi

	export http_proxy=$proxy_address
	export https_proxy=$proxy_address
	export HTTP_PROXY=$proxy_address
	export HTTPS_PROXY=$proxy_address

	export no_proxy=127.0.0.0/8,localhost,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fe80::/10
	export NO_PROXY=$no_proxy
}

main "$@"
